package com.snail.poker.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.snail.poker.uitls.Constant;
import com.snail.poker.uitls.DateUtil;
import com.snail.poker.web.PageContext;

/**
 * 数据分页的拦截器
 * 
 * @author Snail
 * 
 */
public class PageInterceptor extends AbstractInterceptor {

	private static Log log = LogFactory.getLog(PageInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = (HttpServletRequest) invocation
				.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
		PageContext.setPageSize(getPageSize(request));
		PageContext.setOffset(getPageOffset(request));
		PageContext.setBeginTime(getBeginTime(request));
		PageContext.setEndTime(getEndTime(request));

		return invocation.invoke();
	}

	private Date getEndTime(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String endTime = (request.getParameter(Constant.END_KEY) == null || request
				.getParameter(Constant.END_KEY).isEmpty()) ? "9999-12-31 23:59:59"
				: request.getParameter(Constant.END_KEY) + " 23:59:59";
		Date end = DateUtil.toDate(endTime);
		return end;
	}

	private Date getBeginTime(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String beginTime = (request.getParameter(Constant.BEGIN_KEY) == null || request
				.getParameter(Constant.BEGIN_KEY).isEmpty()) ? "1970-01-01 08:00:00"
				: request.getParameter(Constant.BEGIN_KEY) + " 00:00:00";
		Date begin = DateUtil.toDate(beginTime);
		return begin;
	}

	// Getter & Setter
	private int getPageOffset(HttpServletRequest request) {
		int offset = 0;
		try {
			int page = Integer
					.parseInt(request.getParameter(Constant.PAGE_KEY));
			offset = PageContext.getPageSize() * page
					- PageContext.getPageSize();
		} catch (NumberFormatException ignore) {
		}

		log.debug("set pager offset: " + offset);
		return offset;
	}

	private int getPageSize(HttpServletRequest request) {
		// 由session中取得用户自定义分页参数
		int pageSize = 10;
		try {
			pageSize = Integer.parseInt(request
					.getParameter(Constant.PAGE_SIZE));
			if (pageSize == 0) {
				pageSize = 10;
			}
		} catch (NumberFormatException ignore) {
		}
		log.debug("set pager size: " + pageSize);
		return pageSize;
	}
}